package day1;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Collection;
import java.util.Collections;

public class SolrTest {
    SolrClient c;
    @Before//产生连接
    public void init(){
        String url="http://hzn100:8983/solr/first";
        c=new HttpSolrClient.Builder(url).build();
    }

    @After//提交并关闭连接
    public void destry()throws Exception{
        c.commit();
        c.close();
    }

    @Test
    public void insert()throws Exception{
        SolrInputDocument b= new SolrInputDocument();
        b.addField("id","1");
        b.addField("name","侠客行");
        b.addField("price","12");
        c.add(b);

        b= new SolrInputDocument();
        b.addField("id","2");
        b.addField("name","天龙八部");
        b.addField("price","17");
        c.add(b);

        b= new SolrInputDocument();
        b.addField("id","3");
        b.addField("name","西游记");
        b.addField("price","9");
        c.add(b);

        b= new SolrInputDocument();
        b.addField("id","4");
        b.addField("name","东周列国传");
        b.addField("price","78");
        c.add(b);
    }

    @Test
    public void delete()throws Exception{
        //c.deleteById("1");
        //c.deleteByQuery("name:西");
        c.deleteByQuery("id:*");
    }

    @Test
    public void update()throws Exception{
        SolrInputDocument b= new SolrInputDocument();
        b.addField("id","1");
        b.addField("name","小李飞刀");
        b.addField("price","78");
        c.add(b);
    }

    @Test
    public void query()throws Exception{
        //设置查询条件
        SolrQuery q=new SolrQuery();
        //q.setQuery("name:小");
        //q.setQuery("name:*");
        q.setQuery("*:*");

        //按哪个字段排序
        q.setSort("price",SolrQuery.ORDER.asc);

        //执行查询
        QueryResponse resp=c.query(q);

        //解析查询结果
        SolrDocumentList res=resp.getResults();
        long num=res.getNumFound();
        System.out.println("数量："+num);
        for(int i=0;i<num;i++){
            SolrDocument d=res.get(i);
            Collection<String>col= d.getFieldNames();
            for(String k:col){
                System.out.println(k+":"+d.get(k));
            }
        }
    }
}
